import { AnyAction } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import { fakeSubmitForm, getUser } from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    submitRegularForm: Effect;
  };
}
const Model: ModelType = {
  namespace: 'manageUserInfo',

  state: {
    user: {}
  },

  effects: {
    *init(_, { put }) {
      yield put({ type: 'getUser' });
    },
    *submitRegularForm({ payload }, { call }) {
      const response = yield call(fakeSubmitForm, payload);
      if (response.resultCode === 'ok') {
        message.success('用户信息修改成功');
      }
    },
    *getUser(_, { call, put }) {
      const response = yield call(getUser);

      if (response.resultCode === 'ok') {
        yield put({
          type: 'save',
          payload: response.content
        });
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        user: payload,
      };
    },
  },
};

export default Model;
